package com.leyou.item.controller;

import com.leyou.common.pojo.PageResult;
import com.leyou.item.pojo.Brand;
import com.leyou.item.service.BrandService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    @GetMapping("page")
    public ResponseEntity<PageResult<Brand>> queryBrandByPage(
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "rows",defaultValue = "10") Integer rows,
            @RequestParam(value = "sortBy",required = false)String sortBy,
            @RequestParam(value = "desc",required = false)Boolean desc,
            @RequestParam(value = "key",required = false)String key
    ){
        PageResult<Brand> pageResult=brandService.page(page,rows,sortBy,desc,key);
        if (pageResult != null && pageResult.getItems().size()!=0){
            return ResponseEntity.ok(pageResult);
        }
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); //204
    }

    /**
     * 保存品牌,并同时获取品牌对应的分类id,由于spirngMVC的消息转化器可以自动的把有特征字符串转为集合数组,所以直接转换
     * @param brand
     * @param cids
     * @return
     */
       //请求参数为{"name":"黑马","image","","cids":"76","letter":"H"}
        //如果请求参数为json可以用RequestBody接收(前提:json数据必须有对应实体类)
    @PostMapping
    public ResponseEntity<Void> addBrand(Brand brand, @RequestParam("cids")List<Long> cids){
        this.brandService.addBrand(brand,cids);
        return ResponseEntity.status(HttpStatus.CREATED).build(); //201表示添加成功
    }


    @PutMapping
    public ResponseEntity<Void> updateBrand(Brand brand,@RequestParam("cids") List<Long> cids){

        this.brandService.updateBrand(brand,cids);

        return ResponseEntity.status(HttpStatus.CREATED).build();//返回201表示注册完成

    }

    @DeleteMapping("bid/{bid}")
    public ResponseEntity<Void> deleteBrand(@PathVariable("bid") Long bid){
        brandService.deleteBrand(bid);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); //返回204删除成功
    }

}
